package com.itheima.web.controller.system;

import com.github.pagehelper.PageInfo;
import com.itheima.core.BaseServlet;
import com.itheima.domain.system.Dept;
import com.itheima.service.system.DeptService;
import com.itheima.service.system.impl.DeptServiceImpl;
import com.itheima.utils.BeanUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 平台系统管理  -> 部门管理(控制层)
 */
@WebServlet("/system/dept/*")
public class DeptServlet extends BaseServlet {
    private DeptService deptService = new DeptServiceImpl();
    /**
     * 分页查询
     */
    public String list(HttpServletRequest request, HttpServletResponse response) throws Exception{
        /*获取表单数据*/
        String pageNum = request.getParameter("pageNum");
        String pageSize = request.getParameter("pageSize");
        if(StringUtils.isBlank(pageNum)){
           pageNum="1";
        }
        if(StringUtils.isBlank(pageSize)){
            pageSize="10";
        }
        /*调用Service*/
        PageInfo<Dept> pageInfo = deptService.queryPage(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
        /*回显数据*/
        request.setAttribute("page",pageInfo);
        return "/WEB-INF/pages/system/dept/list.jsp";
    }
    /**
     * 跳转到add.jsp页面
     */
    public String toAdd(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //查询所有的部门
        List<Dept> list = deptService.findAll();
        request.setAttribute("deptList",list);
        return "/WEB-INF/pages/system/dept/add.jsp";
    }
    /**新增*/
    public String save(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //获取表单数据
        Dept dept = BeanUtil.fillBean(request, Dept.class, "yyyy-MM-dd");
        //调用Service
        deptService.save(dept);
        //页面跳转
        return "/system/dept/list";
    }
    /**
     跳转到编辑页面
     */
    public String toEdit(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String id = request.getParameter("id");
        Dept dept = deptService.findById(id);
        List<Dept> list = deptService.findAll();
        request.setAttribute("deptList",list);
        request.setAttribute("dept",dept);
        return "/WEB-INF/pages/system/dept/update.jsp";
    }
    /**
     更新
     */
    public String edit(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //获取表单数据
        Dept dept = BeanUtil.fillBean(request, Dept.class, "yyyy-MM-dd");
        //调用Service
        deptService.update(dept);
        //页面跳转
        return "/system/dept/list";
    }
    /**
     删除
     */
    public String delete(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String[] deptids = request.getParameterValues("id");
        deptService.deleteById(deptids);
        return "/system/dept/list";
    }
}
